package com.hand.app.service.impl;

import javax.annotation.Resource;

import com.hand.app.service.OrderStatusService;
import com.hand.domain.content.OrderStatus;
import com.hand.domain.entity.SoHeader;
import com.hand.domain.repository.SoHeaderRepository;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.oauth.DetailsHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderStatusServiceImpl implements OrderStatusService {

    @Resource
    private SoHeaderRepository soHeaderRepository;

    /**
     * @param soHeader
     * @param submitCode
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void validate(SoHeader soHeader, int submitCode) {
        // 查出对应 订单头id 的相关信息
        SoHeader selectedHeader = soHeaderRepository.selectByPrimaryKey(soHeader.getSoHeaderId());
        if(selectedHeader == null) {
            // 当前订单不存在, 抛出异常
            throw new CommonException("------该订单不存在-----");
        }
        // 当前订单存在
        String orderStatus = selectedHeader.getOrderStatus();
        String newOrderStatus = "";
        switch (submitCode) {
            case 0 :
                if(!selectedHeader.getCreatedBy().equals(DetailsHelper.getUserDetails().getUserId())) {
                    throw new CommonException("您和单据创建者身份不一致！");
                }
                if(!orderStatus.equals(OrderStatus.NEW) && !orderStatus.equals(OrderStatus.REJECTED)) {
                    throw new CommonException("当前订单状态不为 NEW/REJECTED,无法执行该操作!");
                }
                newOrderStatus = OrderStatus.SUBMITED;
                break;
            case 1 :
                // 校验当前用户角色是否为SALE_MANAGER_xxx，否则报错
                if(!orderStatus.equals(OrderStatus.SUBMITED)) {
                    throw new CommonException("当前订单状态不为 SUBMITED,无法执行该操作!");
                }
                newOrderStatus = OrderStatus.APPROVED;
                break;
            case 2 :
                // 校验当前用户角色是否为SALE_MANAGER_xxx，否则报错
                if(!orderStatus.equals(OrderStatus.SUBMITED)) {
                    throw new CommonException("当前订单状态不为 SUBMITED,无法执行该操作!");
                }
                newOrderStatus = OrderStatus.REJECTED;
                break;
            default: ;
        }
        // 修改当前单据状态为点击的动作状态，条件为订单头id
        selectedHeader.setOrderStatus(newOrderStatus);
        soHeaderRepository.updateByPrimaryKey(selectedHeader);
    }
}